package com.javaweb.common.security.utils;

import com.javaweb.common.security.entity.LoginUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;

/**
 * 自定义权限认证
 */
@Service("jw")
public class PermissionUtils {

    // 拥有所有权限标识
    private static final String ALL_PERMISSION = "*:*:*";

    /**
     * 验证用户是否拥有某个节点权限（此方法参数参考shiro权限节点标识命令）
     *
     * @param permission 权限节点参数
     * @return
     */
    public boolean hasPermission(String permission) {
        if (StringUtils.isEmpty(permission)) {
            return false;
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isEmpty(loginUser) || CollectionUtils.isEmpty(loginUser.getAuthorities())) {
            return false;
        }
        return hasPermissions(loginUser.getAuthorities(), permission);
    }

    /**
     * 判断某个节点权限是否在权限列表中
     *
     * @param authorities 权限列表
     * @param permission  节点权限标识
     * @return
     */
    private boolean hasPermissions(Collection<? extends GrantedAuthority> authorities, String permission) {
        return authorities.stream().map(GrantedAuthority::getAuthority).filter(StringUtils::hasText)
                .anyMatch(x -> ALL_PERMISSION.contains(x) || PatternMatchUtils.simpleMatch(permission, x));
    }

}
